import time
from concurrent.futures.thread import ThreadPoolExecutor

from client import Client
import threading

from ds.GlobalVarable import imageQueue, clientQueue


class JpegStreamer:
    threadPool = ThreadPoolExecutor(max_workers=2)

    class JpegStreamerThread(threading.Thread):
        def __init__(self):
            super().__init__()
            self.currentJPEG = None
            self.lock = threading.RLock()

        def run(self) -> None:
            while True:
                self.currentJPEG = imageQueue.get()
                # time.sleep(0.1)
                self.sendJPEGToClients(self.currentJPEG)

        def sendJPEGToClients(self, image):
            for currentClient in clientQueue.queue:
                currentClient.registerImage(image)
                JpegStreamer.threadPool.submit(currentClient.run)

    def addClient(self, clientConnection):
        newClient = Client(clientConnection)
        newClient.sendHeader()
        clientQueue.put(newClient)

    def start(self):
        jpegStreamerThread = JpegStreamer.JpegStreamerThread()
        jpegStreamerThread.start()
